import { defineStore } from "pinia";
import { onMounted, ref } from 'vue'

export const useTodoStore = defineStore('todoStore', () => {
  const todos = ref([])

  // const todos = ref([
  //   {
  //     id: '1682921653087',
  //     content: '学习CSS框架',
  //     createTime: '2023/5/1 8:14:13'
  //   },
  //   {
  //     id: '1682921803355',
  //     content: '学习JS算法',
  //     createTime: '2023/5/1 10:34:23'
  //   },
  //   {
  //     id: '1682921831750',
  //     content: '学习Vue框架',
  //     createTime: '2023/5/1 14:04:55'
  //   }
  // ])

  const addTodo = (newContent) => {
    const current = new Date()
    const id = current.getTime().toString()
    const time = current.toLocaleString()
    const todo = {
      id: id,
      content: newContent,
      createTime: time,
      complated: false
    }
    todos.value.unshift(todo)
  }

  const fetchTodos = async () => {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/todos?_limit=5"
    )
    const rawTodos = await response.json();
    todos.value = rawTodos.map((todo) => ({
      id: todo.id,
      content: todo.title,
      completed: todo.completed
    }))
  }

  onMounted(() => {
    fetchTodos()
  });

  return {
    todos,
    addTodo
  }
})